package com.qianheng.kit.base.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

@Slf4j
public class EasyExcelUtil {
    public static <T> List<T> loopRead(Collection<File> files, Class<T> tClass, int headRowNumber) {
        if (CollectionUtils.isEmpty(files)) {
            return Collections.emptyList();
        }
        List<T> result = new ArrayList();
        try {
            for (File file : files) {
                result.addAll(readFirstSheet(file.getCanonicalPath(), tClass, headRowNumber));
            }
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败", e);
        }
        return result;
    }

    /**
     * 读取Excel的第一个sheet
     *
     * @param filePath
     * @param tClass
     * @param headRowNumber
     * @param <T>
     * @return
     */
    public static <T> List<T> readFirstSheet(String filePath, Class<T> tClass, int headRowNumber) {
        List<T> result = new LinkedList<>();
        log.info("读文件:" + filePath);
        try (ExcelReader excelReader = EasyExcel.read(filePath).build()) {
            ReadSheet sheet = EasyExcel.readSheet(0)
                    .head(tClass)
                    .headRowNumber(headRowNumber)
                    .registerReadListener(new PageReadListener<T>(dataList -> {
                        for (T data : dataList) {
                            result.add(data);
                        }
                    }))
                    .build();

            excelReader.read(sheet);
        }
        return result;
    }
}
